const splitRGB = data => {
  const len = data.length / 4
  const rgba = {
    red: new Uint8Array(len),
    green: new Uint8Array(len),
    blue: new Uint8Array(len),
    alpha: new Uint8Array(len)
  }

  let iterator = 0
  for (let i = 0; i < data.length; i += 4, iterator++) {
    rgba.red[iterator] = data[i]
    rgba.green[iterator] = data[i + 1]
    rgba.blue[iterator] = data[i + 2]
    rgba.alpha[iterator] = data[i + 3]
  }

  return rgba
}

const mountRGB = ({red, green, blue, alpha, arr }) => {
  // const arr = new Uint8ClampedArray(red.length * 4)
  const length = arr.length
  let iterator = 0

  for (let i = 0; i < length; i += 4) {
    arr[i] = red[iterator]
    arr[i + 1] = green[iterator]
    arr[i + 2] = blue[iterator]
    arr[i + 3] = alpha[iterator]

    iterator++
  }

  return arr
}

const plotFiltered = (signal, plotContext) => {
  const { width, height } = plotContext.canvas

  const imgData = plotContext.getImageData(0, 0, width, height)
  const dataArr = new Uint8ClampedArray(imgData.data.length)

  for (let i = 0; i < signal.length; i += 4) {
    dataArr[i] = signal[i]
    dataArr[i + 1] = signal[i + 1]
    dataArr[i + 2] = signal[i + 2]
    dataArr[i + 3] = 255
  }

  imgData.data.set(dataArr)
  plotContext.putImageData(imgData, 0, 0)
}

const removeAlpha = data => {
  const arr = new Uint8ClampedArray(data.length / 4 * 3)

  let iterator = 0
  for (let i = 0; i < data.length; i += 4, iterator += 3) {
    arr[iterator] = data[i]
    arr[iterator + 1] = data[i + 1]
    arr[iterator + 2] = data[i + 2]
  }

  return arr
}
